package com.kuangchi.test.service;

import com.kuangchi.test.dao.UserDao;
import com.kuangchi.test.hash.HashCodeService;
import com.kuangchi.test.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @类描述：
 * @项目名称：
 * @包名： com.kuangchi.test.service
 * @类名称：UserService
 * @创建人：YIHANG.XU
 * @创建时间：2021/12/22:32 下午
 * @修改人：YIHANG.XU
 * @修改时间：2021/12/22:32 下午
 * @修改备注：
 * @Copyright
 */
@Service
public class UserService {
    //表数量
    private final static int tableCount = 5;
    @Autowired
    private UserDao userDao;
    @Autowired
    private HashCodeService hashCodeService;

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 8, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    public boolean addUserList(List<UserVo> userVoList) {
        //存储表key
        Set<String> mapSet = new HashSet<>();
        Map<String, List<UserVo>> listMap = new HashMap<>();
        for (UserVo userVo : userVoList) {
            String tableCode = hashCodeService.getTableCode(userVo.getUserId());

            boolean contains = mapSet.contains(tableCode);
            if (contains) {
                List<UserVo> userVos = listMap.get(tableCode);
                userVos.add(userVo);
            } else {
                mapSet.add(tableCode);
                List<UserVo> list = new ArrayList<>();
                list.add(userVo);
                listMap.put(tableCode, list);
            }

        }
        listMap.forEach((k, v) -> {
            threadPoolExecutor.execute(() -> {
                String tabelName = "User_" + k;
                userDao.addUser(tabelName, v);
            });
        });


        return true;
    }


    private int tabeleHase(String userId) {
        return Math.abs(userId.hashCode()) % tableCount;
    }


}
